package com.edu.gdkm.servlet.order;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

import com.edu.gdkm.dao.dypDao;
import com.edu.gdkm.util.cookiesUtil;

@WebServlet("/placeOrderServlet")
public class placeOrderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /* 从前端页面表单获取数据 */

        cookiesUtil util = new cookiesUtil();

        String all = req.getParameter("all");                           // 总价
        String filmId = req.getParameter("filmId");                     // 电影名
        String userId = util.splitCookies(util.findCookie(req.getCookies(), "dyp_user"))[1];
        String nums = req.getParameter("nums");

        try {
            // 打开数据库
            dypDao dao = new dypDao();
            // 订单插入
            String val = "\"\", "+userId+", "+all+", now()";
            dao.insert("orders", val);
            // 执行
            for (int i = 0; i < Integer.parseInt(nums) ; i++) {
                String oid = dao.findMaxId("oid", "orders");    // 获取新增的ID
                // 电影票插入
                val = "\"\", "+oid+", "+filmId+", "+userId+", "+str(randomInfo())+", date_sub(now(), interval -5 day), 1";
                dao.insert("filmegener", val);
            }
            dao.close();
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        // 重定向 => 电影票 Servlet
        resp.sendRedirect(req.getContextPath()+"/ticketServlet");
    }
    /**
     * 随机生成座位信息
     * */
    public String randomInfo() {
        return randomEn() + "厅" + randomNum(1, 10) + "排" + randomNum(1, 10) + "座";
    }

    /**
     * 随机生成数字（范围）
     * */
    public int randomNum(int min, int max) {
        return  (int) (Math.random() * max + min);
    }

    /**
     * 随机五个字母
     * */
    public String randomEn(){
        String[] en = {"A", "B", "C", "E", "F"};
        return en[randomNum(0, 4)];
    }

    public String str(String s){
        return '"'+s+'"';
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
